import datetime
import json

from sqlalchemy import and_

from webapp.extensions import AppException
from webapp.models import VCourse, Plan, Session, Grade, VTeacher, Dept, DictDetail, Course, db, CourseTable, Room


class CourseService:
    @staticmethod
    def query_all(page=0, size=9999, **kwargs) -> list:
        create_times = kwargs.get('createTime')
        classname = kwargs.get('classname')
        not_empty = classname or create_times
        query = []
        if classname:
            query.append((VCourse.classname.like(f'%{classname}%')))
        if create_times and len(create_times) >= 2:
            query.append((VCourse.create_time.between(create_times[0], create_times[1])))
        result = VCourse.query.filter(*query).paginate(int(page) + 1, per_page=int(size),
                                                       error_out=False)
        return result

    @staticmethod
    def query_all_options():
        choiceOpts = {
            'plans': [],
            'sessions': [],
            'weeksum': [],
            'classes': [],
            'resources': [],
            'placetypes': [],
            'teachers': [],
            'campus': []
        }
        plansFromDB = Plan.query.all()
        for plan in plansFromDB:
            keyv = {
                'label': plan.planname,
                'value': plan.id
            }
            choiceOpts.get('plans').append(keyv)

        sessionFromDB = Session.query.all()
        for session in sessionFromDB:
            keyv = {
                'label': session.session,
                'value': session.id
            }
            choiceOpts.get('sessions').append(keyv)

        cur_session_date = datetime.date.today()
        session = Session.query.filter(and_(
            Session.begin_date <= cur_session_date,
            Session.end_date >= cur_session_date
        )).order_by(Session.create_time).first()
        if session is None:
            keyv = {
                'label': '第{}周'.format(1),
                'value': 1
            }
            choiceOpts.get('weeksum').append(keyv)
        else:
            for i in range(0, session.weeksum):
                keyv = {
                    'label': '第{}周'.format(i + 1),
                    'value': i + 1
                }
                choiceOpts.get('weeksum').append(keyv)

        grades = Grade.query.all()
        for grade in grades:
            keyv = {
                'label': grade.classname,
                'value': grade.id
            }
            choiceOpts.get('classes').append(keyv)

        teachers = VTeacher.query.all()
        for teacher in teachers:
            keyv = {
                'label': teacher.nick_name,
                'value': teacher.user_id
            }
            choiceOpts.get('teachers').append(keyv)
        campus = Dept.query.all()
        for campu in campus:
            keyv = {
                'label': campu.name,
                'value': campu.dept_id
            }
            choiceOpts.get('campus').append(keyv)
        placetypes = DictDetail.query.filter(DictDetail.dict_id == 8).all()
        for placetype in placetypes:
            keyv = {
                'label': placetype.label,
                'value': placetype.detail_id
            }
            choiceOpts.get('placetypes').append(keyv)
        resources = Room.query.all()
        for resource in resources:
            keyv = {
                'label': resource.roomname,
                'value': resource.id
            }
            choiceOpts.get('resources').append(keyv)
        return choiceOpts

    @staticmethod
    def create(curr_course: Course):
        coursetable = CourseTable.query.filter(CourseTable.cname == curr_course.cname).one_or_none()
        if coursetable:
            raise AppException(f'{curr_course.cname}已存在!')
        curr_course.create_time = datetime.datetime.now()
        coursetable = CourseTable(
            cname=curr_course.cname,
            plan=curr_course.plan,
            seweek='{},{}'.format(curr_course.startW, curr_course.endW),
            teachclass=curr_course.teachclass,
            startW=curr_course.startW,
            endW=curr_course.endW,
            placetype=curr_course.placetype,
            teacher=curr_course.teacher,
            resource=curr_course.resource,
            sessionId=curr_course.sessionId,
            campus=curr_course.campus,
            status=0
        )
        db.session.add(coursetable)
        db.session.commit()

    @staticmethod
    def update(curr_course: Course):
        coursetable = CourseTable.query.filter(CourseTable.id == curr_course.id).one_or_none()
        if coursetable is None:
            raise AppException(f'{curr_course.cname}不存在!')
        coursetable.cname=curr_course.cname
        coursetable.plan=curr_course.plan
        coursetable.seweek='{},{}'.format(curr_course.startW, curr_course.endW)
        coursetable.startW=curr_course.startW
        coursetable.endW = curr_course.endW
        coursetable.teachclass=curr_course.teachclass
        coursetable.placetype=curr_course.placetype
        coursetable.teacher=curr_course.teacher
        coursetable.resource=curr_course.resource
        coursetable.sessionId=curr_course.sessionId
        coursetable.campus=curr_course.campus
        coursetable.update_time=datetime.datetime.now()
        coursetable.update_by=curr_course.update_by
        db.session.commit()

    @staticmethod
    def find_by_id(id):
        courseTable = db.session.query(CourseTable).filter(CourseTable.id == id).one_or_none()
        if courseTable is None:
            raise AppException(f'您所操作的对象已不存在!')
        return courseTable

    @staticmethod
    def delete(course_set):
        if course_set:
            for couse in course_set:
                db.session.delete(couse)
            db.session.commit()
